package model

import (
	"api/database"
	"api/utils/logger"
	"github.com/jinzhu/gorm"
)

/**
 * @Description
 * @Author huan.wang
 * @Date 2021/5/6 12:56 下午
 **/

type DeviceModel struct {
	BaseModel
	gorm.Model
	Name       string `gorm:"column:name"`
	Describe   string `gorm:"column:describe"`
	Key        string `gorm:"column:key"`
	UID        uint
	DeviceType DeviceTypeModel `gorm:"ForeignKey:TypeID"`
	TypeID     uint
	Online     bool
}

func NewDeviceModel() *DeviceModel {
	return &DeviceModel{}
}

func (DeviceModel) TableName() string {
	return "device"
}

func (dm DeviceModel) Insert() (interface{}, error) {
	if err := database.GetDB().Create(&dm).Error; err != nil {
		logger.Error.Println("[Model] insert error", err)
		return nil, err
	}
	var id []uint
	database.GetDB().Raw("select LAST_INSERT_ID() as id").Pluck("id", &id)
	return id[0], nil
}

func (dm DeviceModel) Delete() (interface{}, error) {
	database.GetDB().Model(&dm).Delete(&dm)
	return nil,nil
}

func (dm *DeviceModel) SaveOnlineState() {
	database.GetDB().Model(&dm).Where("name = ? and `key` = ?", dm.UID, dm.Key).Update("online",dm.Online)
}

func (dm DeviceModel) SelectDeviceByUser() (devices []DeviceModel) {
	database.GetDB().Model(&dm).Where("uid = ?", dm.UID).Order("created_at DESC").Preload("DeviceType").Find(&devices)
	return
}

func (dm DeviceModel) SelectDeviceByNameKey() (devices DeviceModel) {
	database.GetDB().Model(&dm).Where("name = ? and `key` = ?", dm.UID, dm.Key).Preload("DeviceType").First(&devices)
	return
}

func (dm DeviceModel) SelectDeviceCountByUser() (value uint) {
	database.GetDB().Model(&dm).Where("uid = ?", dm.UID).Count(&value)
	return
}
